<template>
    <div class="warpper">
        <van-nav-bar safe-area-inset-top placeholder>
            <template #title>
                <van-col>
                    <van-icon name="points" size="20" color="red" />
                </van-col>
                <van-col>我的队伍</van-col>
            </template>
        </van-nav-bar>

        <!-- 菜单行 -->
        <van-row class="menu-row">
            <van-button icon="label-o" type="info" class="menu-btn" @click="isShowLoadSchemeDialog = true"
                :disabled="schemeOptions == null || schemeOptions.length <= 0">
                加载方案
            </van-button>

            <van-button icon="description" type="info" class="menu-btn" @click="addNewScheme(true)">
                新建方案
            </van-button>
            
            <van-button icon="completed" type="info" class="menu-btn" @click="isShowSaveSchemeDialog = true"
                :disabled="schemeOptions == null">
                保存方案
            </van-button>
            
            <van-button icon="failure" type="info" class="menu-btn" @click="isShowDeleteDialog = true"
                :disabled="schemeOptions == null">
                删除方案
            </van-button>
            
            <van-button icon="share-o" type="info" class="menu-btn" @click="onShareScheme"
                :disabled="schemeOptions == null">
                分享方案
            </van-button>

            <van-button icon="upgrade" type="info" class="menu-btn" @click="onExportScheme" 
                :disabled="schemeOptions == null">
                导出方案
            </van-button>
           
            <van-button icon="certificate" type="info" class="menu-btn" @click="isShowInputSchemeDialog=true">
                导入方案
            </van-button>
           
            <van-button icon="plus" type="primary" class="menu-btn" @click="onAddDreamTeam"
                :disabled="schemeOptions == null">
                添加梦境队
            </van-button>
           
            <van-button icon="plus" type="primary" class="menu-btn" @click="onAddFreeTeam"
                :disabled="schemeOptions == null">
                添加自由队
            </van-button>
           
            <van-button icon="question-o" type="warning" class="menu-btn" @click="isShowHelpDialog = true">
                使用帮助
            </van-button>

        </van-row>

        <!-- 角色卡池 -->
        <van-field class="game-box-title" is-link :arrow-direction="isCollapse?'down':'up'" readonly @click="isCollapse=!isCollapse">
            <template #label>
                <span>角色卡池</span>
                <span class="title-tip">(按住角色头像拖入我的卡池中)</span>
            </template>
        </van-field>
        <van-row class="box-row" v-show="!isCollapse">
            <div id="game-box" @drop.prevent.self='dropDrag' @dragover.prevent='overDrag'>
                <template v-for="item in myGameRoles_list">
                    <van-image class="game-role-headimg" :style="{ borderColor: getHeadBorderColor(item) }"
                        :src="item.icon" draggable @dragstart.native='startDrag(item)' />
                </template>
            </div>
        </van-row>

        <!-- 我的卡池 -->
        <van-field class="my-box-title" is-link :arrow-direction="selfCollapse?'down':'up'" readonly @click="selfCollapse=!selfCollapse">
            <template #label>
                <span>我的卡池</span><span class="title-tip">(按住角色头像拖入队伍头像中)</span>
            </template>
        </van-field>
        <van-row class="box-row" v-show="!selfCollapse">
            <div class="my-box-condi mouse-point">
                <van-col v-for="(text,idx) in ['全部','真樱','奥山','圣树','尼罗','众星','S级','A级']" 
                    class="margin-left mouse-point" :key="idx" :class="(selfCondi==idx && idx !=0)?'coler-blue-underline':''"
                    @click="selfCondi=idx">
                    {{ text }}
                </van-col>
              
                <van-col class="color-blue" @click.native="addOnekey">一键添加</van-col>
            </div>
            <div id="my-box" @dragover.prevent='overDrag' @drop.prevent='dropDrag' >
                <template v-for="item in myRoles_list">
                    <div class="role-headimg-div"  :class="myBoxUsedClass(item)" v-show="myBoxDivIsShow(item)"
                        draggable @dragstart='startDrag(item)'>
                        <van-image :src="item.icon"/>
                        <i class="el-icon-remove-outline remove " @click="myBoxRemove(item)"></i>
                        <span>{{ item.per_name }}</span>
                    </div>
                </template>
            </div>
        </van-row>

        <!-- 队伍内容 -->
        <div id="myTeamAutoDiv">
            <!-- 梦境队伍 -->
            <div id="my-dream-team" v-if="current_scheme!=null && current_scheme.dream_team !=null">
                <template  v-for="(team,index) in current_scheme.dream_team">
                    <!-- <my-team-item :teamType="0" :teamIndex="index" :teamData="team"></my-team-item> -->
                    <my-team-item v-model="current_scheme.dream_team[index]"
                        :scheme = "current_scheme"
                        :bossOptions="bossOptions"
                        v-on:reset="onRestTeam('dream', index)"
                        v-on:remove="onRemoveTeam('dream', index)" 
                        v-on:dropDrag="dropDrag"
                        :allRoles_list="allRoles_list">
                        <template>梦境队伍{{ index + 1 }}</template>
                    </my-team-item>
                </template>
            </div>

            <!-- 自由队伍 -->
            <div id="my-free-team" v-if="current_scheme!=null && current_scheme.free_team !=null">
                <template  v-for="(team,index) in current_scheme.free_team">
                    <!-- <my-team-item :teamType="1" :teamIndex="index" :teamData="team"></my-team-item> -->
                    <my-team-item v-model="current_scheme.free_team[index]"
                        v-on:reset="onRestTeam('free', index)" 
                        v-on:remove="onRemoveTeam('free', index)"
                        v-on:dropDrag="dropDrag" 
                        :allRoles_list="allRoles_list">
                        <template>自由配队{{ index + 1 }}</template>
                    </my-team-item>
                </template>
            </div>
        </div>

        <!-- 保存dialog -->
        <van-popup v-if="isShowSaveSchemeDialog" v-model="isShowSaveSchemeDialog"
        closeable round position="bottom" style="height: 30%;" transition-appear>

            <div class="popup-title-container">
                <h3>保存方案</h3>
            </div>

            <div class="popup-content-container">
                <van-cell-group>
                    <van-field
                        v-model="current_scheme.name"
                        placeholder="方案名"
                        :border="false"
                    />

                    <van-field
                        v-model="current_scheme.remark"
                        placeholder="备注"
                        :border="false"
                    />
                </van-cell-group>

                <van-row class="font-center margin-top">
                    <van-button @click="isShowSaveSchemeDialog = false" v-show="!isSaveing">取消</van-button>
                    <van-button @click="saveScheme" type="warning" :loading="isSaveing"> {{ isSaveing ? '正在保存' : '确定' }}</van-button>
                </van-row>
            </div>
        </van-popup>

        <!-- 加载dialog -->
        <van-popup class="isShowLoadSchemeDialog" v-if="isShowLoadSchemeDialog" v-model="isShowLoadSchemeDialog" round position="bottom"
            transition-appear>
            <van-picker title="选择一个方案" show-toolbar :columns="schemeOptions.map(e=>e.name)"
                 @confirm="getSavedScheme" @cancel="isShowLoadSchemeDialog=false">
            </van-picker>
        </van-popup>

        <!-- 新建提示dialog -->
        <van-popup v-if="isShowAbandonDialog" v-model="isShowAbandonDialog" closeable round position="bottom"
            style="height: 30%;" transition-appear>

            <div class="popup-title-container">
                <h3>将丢弃未保存的操作，确定继续吗?</h3>
            </div>

            <div class="popup-content-container">
                <van-row class="font-center margin-top">
                    <van-button class="popup-btn" @click="isShowAbandonDialog = false"  type="warning">
                        取消
                    </van-button>
                    <van-button class="popup-btn" @click="addNewScheme(false); isShowAbandonDialog = false" >
                        继续
                    </van-button>
                </van-row>
            </div>
        </van-popup>

        <!-- 删除提示dialog -->
        <van-popup v-if="isShowDeleteDialog" v-model="isShowDeleteDialog" closeable round position="bottom"
            style="height: 30%;" transition-appear>

            <div class="popup-title-container">
                <h3>确定要删除该方案吗?</h3>
            </div>

            <div class="popup-content-container">
                <van-row class="font-center margin-top">
                    <van-button class="popup-btn" @click="isShowDeleteDialog = false"  type="warning">
                        取消
                    </van-button>
                    <van-button class="popup-btn" @click="onRemoveScheme(); isShowDeleteDialog = false">
                        继续
                    </van-button>
                </van-row>
            </div>
        </van-popup>

        <!-- 导入dialog -->
        <van-popup v-if="isShowInputSchemeDialog" v-model="isShowInputSchemeDialog" closeable round position="bottom"
            style="height: 60%;" transition-appear>

            <div class="popup-title-container">
                <h3>上传文件,或粘贴代码</h3>
            </div>

            <div class="popup-content-container">

                <el-input class="margin-bottom popup-file" ref="file_input" type="file" @change="onFileChange" v-model="input_file"
                    accept=".txt,.json" />

                <el-input class="margin-bottom" type="textarea"  v-model="input_text"
                    :autosize="{ minRows: 15, maxRows: 15 }"
                    :readonly="input_file != null" placeholder="粘贴代码" />
                    
                <van-row class="font-center margin-top">
                    <van-button class="popup-btn" @click="resetInput" v-show="!isSaveing">清空</van-button>
                    <van-button class="popup-btn" @click="isShowInputSchemeDialog = false" v-show="!isSaveing">取消</van-button>
                    <van-button class="popup-btn" @click="inputScheme" type="warning">导入</van-button>
                </van-row>
            </div>
        </van-popup>

        <!-- 导出dialog -->
        <van-popup v-if="isShowExportSchemeDialog" v-model="isShowExportSchemeDialog" closeable round position="bottom"
            style="height: 60%;" transition-appear>

            <div class="popup-title-container">
                <h3>导出方案</h3>
            </div>

            <div class="popup-content-container">
                <el-input class="margin-bottom" type="textarea"  v-model="export_text"
                    :autosize="{ minRows: 15, maxRows: 15 }"
                    readonly placeholder="导出代码" />
                    
                <van-row class="font-center margin-top">
                    <van-button class="popup-btn" @click="saveExportScheme" type="warning">下载文件</van-button>
                </van-row>
            </div>
        </van-popup>

        <!-- 帮助dialog -->
        <van-popup v-if="isShowHelpDialog" v-model="isShowHelpDialog" closeable round position="bottom"
            style="height: 30%;" transition-appear>

            <div class="popup-title-container">
                <h3>前往帮助页面</h3>
            </div>

            <div class="popup-content-container" >
                <system-href ref="syshref" width='400' href="https://www.wolai.com/skyey-engrave/4vDDFc3H5KSeNBnpyGrpii"/> 

                <van-row class="font-center margin-top">
                    <van-button @click="isShowHelpDialog = false" type="warning">取消</van-button>
                    <van-button @click='tohref()' >继续访问</van-button>
                </van-row>
            </div>
        </van-popup>
    </div>
</template>

<script>
import { TeamServer } from '../server/servers';
import html2canvas from 'html2canvas';
import SystemHref from '../sub/SystemHref.vue';
import MyTeamItem from './MyTeamItem'
import { Toast, Notify } from 'vant';
const { ipcRenderer } = window.require('electron')

export default {
    name: "MyTeam",
    components: { MyTeamItem,SystemHref },

    created() {
        let vm = this
        setTimeout(() => {
            vm.getAllRoles();
            vm.getAllBoss();
            vm.addNewScheme(false);
            vm.getSchemeOption();
        }, 2000);
    },

    watch:{
        isCollapse(){
            this.autoSetHeight()
        },

        selfCollapse(){
            this.autoSetHeight()
        },

        selfCondi(){
            this.autoSetHeight()
        },
    },

    data: () => ({
        allRoles_list: [], //全部角色list
        boss_list: [],     //全部bosslist

        bossOptions:null,    //boss列表
        schemeOptions: null, //所有方案名

        current_scheme: null,     //当前方案
        myRoles_list: [],       //当前我的卡池
        myGameRoles_list: [],   //当前角色池

        currentDrag: null,
        isCollapse: false,  //角色池是否折叠
        selfCollapse: false,//我的卡池是否折叠
        selfCondi:0,        //我的卡池过滤条件

        borderColor: {
            "B": "#C0C0C0",
            "A": "#C0C0C0",
            "S": "#FFD700"
        },

        isShowHelpDialog: false,
        isShowAbandonDialog: false,
        isShowDeleteDialog: false,
        isShowSaveSchemeDialog: false,
        isShowLoadSchemeDialog: false,
        isSaveing: false,

        isShowExportSchemeDialog: false,
        export_text: "",

        isShowInputSchemeDialog: false,
        input_text: '',
        input_file: null,
    }),

    methods: {

        test(obj) {
            console.log('test', obj);
        },

        autoSetHeight() {
            //我的卡池容器高度
            let myBoxContainer = document.getElementById("my-box");
            // console.log("autoSetHeight myBoxContainer",myBoxContainer,myBoxContainer.childNodes.length)
            {   
                let childNodes= [].slice.call(myBoxContainer.childNodes) //子元素转为数组
                let showDiv = childNodes.filter(e=>e.style.display != 'none') //过滤掉隐藏元素
                let num = showDiv.length;
                let height =Math.max((Math.trunc ((num-1)/10)+1)*54,54)
                 myBoxContainer.style.height = height + 'px'
            }

            //队伍容器高度
            {
                //底部的底边
                let element
                if(this.selfCollapse){
                    //折叠取 my-box-title
                    element = document.querySelector(".my-box-title")

                }else{
                    //展开取 #my-box
                    element = myBoxContainer
                }

                //底部的顶边
                let bottom = document.querySelector("#bottom-tabber");
                let height = bottom.getBoundingClientRect().top - element.getBoundingClientRect().bottom
                let container = document.querySelector("#myTeamAutoDiv");
                container.style.height = height + 'px'
            }
        },

        //遍历父元素 寻找id
        findParentId(dom) {
            let parent = dom.parentElement;
            while (parent && !parent.id) {
                parent = parent.parentElement;
            }
            return parent.id;
        },

        //触发拖拽事件 ev.target:触发事件的iv
        startDrag(item) {
            console.log("startDrag",item)
            this.currentDrag = item;
        },

        //拖拽时鼠标经过事件
        overDrag(ev) {
            // console.log("overDrag", ev.target);
        },

        //拖拽结束后
        //data: 1游戏池拖到我的卡池 忽略
        //      2我的卡池到队伍头像 data传 current_scheme.dream_team.data[]对象
        //event: 默认变量，拖动事件,event.target.结束拖拽时所在的div
        dropDrag(data) {
            console.log("dropDrag",data,this.currentDrag)
            if (!this.currentDrag) {
                return;
            }

            let ev = event;
            let domid = ev.target.id || this.findParentId(ev.target);
            // console.log("dropDrag", domid, ev.target)

            //<角色卡池>移动到<我的卡池>
            if (domid == "my-box" && this.currentDrag.from == "game-box") {
                this.myGameRoles_list.some((e, i) => {
                    if (e == this.currentDrag) {
                        this.myGameRoles_list.splice(i, 1);
                        return true;
                    }
                });

                //当游戏卡池空了 自动折叠
                this.isCollapse = this.myGameRoles_list.length <= 0;

                this.myRoles_list.push(this.currentDrag);
                this.currentDrag.from = "my-box";
                this.currentDrag = null;

                //重设高度
                this.$nextTick().then(() => {
                    this.autoSetHeight();
                });
                return;
            }

            //<我的卡池>移动到<梦境-队伍头像>
            if (domid == 'my-dream-team' && this.currentDrag.from == "my-box") {
                console.log("<我的卡池>移动到<梦境-队伍头像>", data, this.currentDrag);

                //校验是否已经使用的角色
                if (this.current_scheme.used.some(e => {
                    return e == this.currentDrag.id;
                })) {
                    Notify({ type: 'warning', message: "\n梦境队伍不能使用重复的角色哦!", duration: 2000 });
                    return;
                }

                this.current_scheme.used.push(this.currentDrag.id);//记录使用过的角色

                //删除被替换的角色的记录id
                if(data.role_id != null){
                    this.current_scheme.used.some((e,i)=>{
                        if(e==data.role_id){
                            this.current_scheme.used.splice(i,1);
                            return true;
                        }
                    })
                }

                data.role_id = this.currentDrag.id;
                data.role_icon = this.currentDrag.icon;
                data.role_name = this.currentDrag.per_name + "·" + this.currentDrag.real_name;
                data.role_class = this.currentDrag.class;
                this.currentDrag = null;
                return;
            }

            //<我的卡池>移动到<自由-队伍头像>
            if (domid == 'my-free-team' && this.currentDrag.from == "my-box") {
                // console.log("<我的卡池>移动到<自由-队伍头像>", data, this.currentDrag);

                //遍历父对象 找出所在队伍
                let team;
                this.current_scheme.free_team.some(e => {
                    return e.data.some(e1 => {
                        if (e1 == data) {
                            team = e;
                            return true;
                        }
                    });
                });

                if (!team) {
                    console.log("未找到current_scheme.free_team[]队伍信息");
                    return;
                }

                //校验同一队不能使用重复角色
                if (team.data.some(e => {
                    return e.role_id == this.currentDrag.id;
                })) {
                    Notify({ type: 'warning', message: "\n同一个队伍不能使用重复的角色哦", duration: 2000 });

                    return;
                }

                data.role_id = this.currentDrag.id;
                data.role_icon = this.currentDrag.icon;
                data.role_name = this.currentDrag.per_name + "·" + this.currentDrag.real_name;
                data.role_class = this.currentDrag.class;
                this.currentDrag = null;
                this.$forceUpdate()
                return;
            }

            //错误提示
            if (domid == "my-dream-team" || domid == 'my-free-team' && this.currentDrag.from == "game-box") {
                Notify({ type: 'warning', message: "\n先添加进我的卡池再继续操作哦!", duration: 2000 });
            }

            this.currentDrag = null;
        },

        //一键添加所有角色
        addOnekey(){
            this.isCollapse = true;
            this.selfCollapse = false;

            //遍历元素 设置.from = "my-box";
            this.myGameRoles_list.forEach(e=>{
                this.myRoles_list.push(e)
                e.from = 'my-box'
            })

            this.myGameRoles_list = [];
            this.$nextTick().then(() => {
                this.autoSetHeight();
            });
        },

        myBoxDivIsShow(item){
            // console.log("myBoxDivIsShow selfCondi",this.selfCondi)
            // console.log("myBoxDivIsShow item",item)
            let rs = true

            switch(this.selfCondi){
                case 1:
                    rs =  item.class=="真樱";break;
                case 2:
                    rs =  item.class=="奥山";break;
                case 3:
                    rs = item.class=="圣树";break;
                case 4:
                    rs = item.class=="尼罗";break;
                case 5:
                    rs = item.class=="众星";break;
                case 6:
                    rs = item.rank=="S";break;
                case 7:
                    rs = item.rank=="A";break;
                default:
                    rs = true;
            }

            //@TODO
            //我的卡池变动后要重新计算div高度，
            //这里通过延时调用计算，但这种实现的并不太好(会多次反复调用)
            //最好能监听到上级div的更新，然后再调用autoSetHeight
            setTimeout(()=>this.autoSetHeight(),500)
            
            return rs;
        },

        myBoxUsedClass(item){
            // console.log('myBoxUsedClass',item)
            //根据id 查找梦境队伍是否存在
            if(this.current_scheme && this.current_scheme.dream_team){
                let rs = this.current_scheme.dream_team.some(e=>{
                    return e.data.some(e1=>{
                        return e1.role_id == item.id
                    })

                })

                return rs?  'role-headimg-div-used':''
            }
            return ''
        },

        myBoxRemove(item) {
            this.isCollapse = false;
            item.from = "game-box";
            this.myGameRoles_list.push(item);

            this.myRoles_list.some((e, i) => {
                if (e == item) {
                    this.myRoles_list.splice(i, 1);
                    return;
                }
            });
        },

        getAllRoles() {
            // console.log("MyTeam.vue getAllRoles")
            this.allRoles_list = TeamServer.queryAllRoles();
            // this.allRoles_list.forEach(e=>{
            //     console.log(e.per_name,e.real_name)
            // })
        },

        getAllBoss() {
            // console.log("MyTeam.vue getAllBoss")
            this.boss_list = TeamServer.queryAllBoss();
            this.bossOptions = this.boss_list.map(e=>({
                value:e.id,
                label:e.real_name,
                name:e.per_name+" "+e.real_name, //+ (e.nick_name?` (${e.nick_name})`:""),
                icon:e.icon
            }))

            // console.log(this.boss_list)
            // console.log(this.bossOptions)
        },

        getSchemeOption() {
            this.schemeOptions = TeamServer.queryAllSchemeNames();
            // console.log("getSchemeOption", this.schemeOptions);
        },

        initScheme() {
            if (this.allRoles_list) {
                let list = JSON.parse(JSON.stringify(this.allRoles_list));
                this.myGameRoles_list = list.map(e => {
                    return Object.assign(e, { from: "game-box" });
                });
            }

            this.isCollapse = false;
            this.myRoles_list = [];
            this.current_scheme = TeamServer.getNewScheme();
        },

        applyScheme(scheme) {
            // console.log("applyScheme", scheme);
            this.current_scheme = null;
            this.myRoles_list = [];
            this.myGameRoles_list = [];

            let gamebox = [], mybox = [];
            JSON.parse(JSON.stringify(this.allRoles_list)).forEach(e => {
                if (scheme.box.some(e1 => (e.id == e1))) {
                    mybox.push(Object.assign(e, { from: "my-box" }));
                } else {
                    gamebox.push(Object.assign(e, { from: "game-box" }));
                }
            });

            this.current_scheme = scheme;
            this.myRoles_list = mybox;
            this.myGameRoles_list = gamebox;

            //如果游戏卡池空了 自动折叠
            this.isCollapse = this.myGameRoles_list.length <= 0;

            this.$nextTick().then(() => {
                this.autoSetHeight();
            });
        },

        getSavedScheme(value, index) {
            // console.log('getSavedScheme',value, index)
            this.isShowLoadSchemeDialog = false;
            let data = this.schemeOptions[index]
            let id =data.id
            let scheme = TeamServer.queryScheme(id);
            console.log("查询到了scheme", scheme);
            this.applyScheme(scheme);
            this.isCollapse = true; //加载后折叠游戏卡池
            this.selfCollapse = true; //加载后折叠我的卡池
        },

        saveScheme() {
            console.log("保存方案", this.current_scheme);

            //校验方案名
            if (this.current_scheme.name == "" || this.current_scheme.name == null) {
                Notify({ type: 'warning', message: "\n请输入方案名哦!", duration: 2000 });
                return;
            }

            //校验id
            if (this.current_scheme.id == "" || this.current_scheme.id == null) {
                console.log("方案没有id")
                return;
            }

            this.isSaveing = true;
            let flag = TeamServer.saveScheme(this.current_scheme, this.myRoles_list);

            //至少留3秒 给lokijs读写的时间
            setTimeout(() => {
                this.isSaveing = false;
                this.isShowSaveSchemeDialog = false;

                if (flag) {
                    Notify({ type: 'success', message: "\n保存成功!", duration: 2000 });
                } else {
                    Notify({ type: 'warning', message: "\n保存失败!", duration: 2000 });
                }
                this.getSchemeOption(); //重新加载 加载列表
            }, 3000);
        },

        getHeadBorderColor(item) {
            return this.borderColor[item.rank];
        },

        //新增方案
        //@param flag是否弹出丢弃提示
        addNewScheme(flag) {
            if (flag) {
                this.isShowAbandonDialog = true;
                return;
            }

            this.current_scheme = TeamServer.getNewScheme();
            this.initScheme();
            this.isCollapse=false
            this.selfCollapse=false
            this.$nextTick().then(() => {
                this.autoSetHeight();
            })
        },

        onExportScheme() {
            this.current_scheme.box = this.myRoles_list.map(e => e.id);
            this.export_text = JSON.stringify(this.current_scheme);
            this.isShowExportSchemeDialog = true;

            //复制到剪贴板
            let area = document.createElement("textarea");
            area.innerText = this.export_text;
            document.body.appendChild(area);
            area.select();
            document.execCommand("Copy");
            document.body.removeChild(area);
            Notify({ type: 'success', message: "\n已复到剪切板~", duration: 2000 });
        },

        saveExportScheme() {
            let contentType = 'application/octet-stream';
            let a = document.createElement('a');
            let blob = new Blob([this.export_text], { 'type': contentType });
            a.href = window.URL.createObjectURL(blob);
            a.download = `导出方案-${this.current_scheme.name}.txt`;
            a.click();
        },

        resetInput(){
            this.input_text = '';
            this.input_file = null;
        },

        onFileChange(ev) {
            // console.log("onFileChange", ev, this.input_file)
            let vm = this;
            let fr = new FileReader();
            let file = this.$refs.file_input.$el.children[0].files[0];

            if (!file) {
                this.input_text = '';
                this.input_file = null;
                return
            }

            fr.readAsText(file);
            fr.onload = function (event) {
                vm.input_text = event.target.result;
                vm.checkInputJson();
            }
        },

        checkInputJson() {
            let data;

            //非空校验
            if (this.input_text == "" || this.input_text == null) {
                Notify({ type: 'warning', message: '\n导入内容不正确哦,请查看帮助', duration: 2000 });
                return false;
            }

            //json转对象
            try {
                data = JSON.parse(this.input_text);
            } catch (e) {
                Notify({ type: 'warning', message: '\n导入内容不正确哦,请查看帮助', duration: 2000 });
                return false;
            }

            return data;
        },

        inputScheme() {
            let scheme = this.checkInputJson();

            if (scheme) {
                //应用数据
                this.applyScheme(scheme)
                this.isShowInputSchemeDialog = false;
                Notify({ type: 'success', message: "\n导入成功,如需保存请手动点击保存按钮哦", duration: 2000 });
            }
        },

        onShareScheme() {
            Toast({
                message: '正在生成图片...',
                position: 'top',
                type: 'loading',
                overlay: true,
                duration: 0
            });

            let element = document.querySelector('#myTeamAutoDiv');

            //长截图实现 
            //克隆元素 设置长宽完全展开
            let _clone = element.cloneNode(true);
            _clone.id += "_clone";
            _clone.style.zIndex = 0
            _clone.style.width = element.scrollWidth + 'px'
            _clone.style.height = element.scrollHeight + 'px'
            document.body.appendChild(_clone)

            //样式调整
            _clone.querySelectorAll(".el-button-group").forEach(e=>e.remove());
            _clone.querySelectorAll(".content-btn-div").forEach(e=>e.remove());

            _clone.querySelectorAll(".title-row").forEach(e=>{
                e.querySelectorAll(".van-col--4").forEach((e1,i)=>{
                    if(i==4){
                        e1.remove();
                    }
                    if(i>=1){
                        e1.style="width:120px";
                    }
                    
                });
            });
            
            _clone.querySelectorAll(".myteam-item-wrapper").forEach(e=>e.style="height:180px");
           
            //end

            html2canvas(_clone, {
                allowTaint: true,  
                taintTest: true,    
                preserveDrawingBuffer: true,
                useCORS: true, //跨域图片处理
            }).then(canvas=> {
                let url = canvas.toDataURL(1); //得到base64编码
                let a = document.createElement("a"); 
                let event = new MouseEvent("click"); 
                a.download = '组队方案分享:'+this.current_scheme.name;
                a.href = url; 
                a.dispatchEvent(event); 
                _clone.remove();
                Toast.clear();
                Notify({ type: 'success', message: "\n分享成功！", duration: 2000 });
            })
        },

        onAddDreamTeam() {
            // console.log("onAddDreamTeam");

            if (!this.current_scheme) {
                this.current_scheme = TeamServer.getNewScheme();
            }

            if (this.current_scheme.dream_team.length >= 4) {
                Notify({ type: 'warning', message: "\n不能继续添加梦境队伍了哦", duration: 2000 });
                return;
            }

            let team = TeamServer.getNewTeam();
            this.current_scheme.dream_team.push(team);
        },

        onAddFreeTeam() {
            // console.log("onAddFreeTeam");

            if (!this.current_scheme) {
                this.current_scheme = TeamServer.getNewScheme();
            }

            let team = TeamServer.getNewTeam();
            this.current_scheme.free_team.push(team);
        },

        queryAllDatas() {
            //角色池
            //我的卡池
            //梦境队伍
            //自由队伍
        },

        removeUsed(team) {
            let array = team.data.map(e => e.role_id);
            this.current_scheme.used = this.current_scheme.used.filter(e => {
                return !array.some(a => a == e);
            })
        },

        onRemoveScheme() {
            if (this.current_scheme == null) {
                return;
            }

            TeamServer.removeScheme(this.current_scheme.id);
            this.initScheme();
            this.getSchemeOption();
        },

        onRemoveTeam(t_type, index) {
            if (t_type == "dream") {
                this.removeUsed(this.current_scheme.dream_team[index]);
                this.current_scheme.dream_team.splice(index, 1);
                return;
            }

            if (t_type == "free") {
                this.current_scheme.free_team.splice(index, 1);
                return;
            }
        },

        onRestTeam(t_type, index) {
            // console.log("onRestTeam")

            //拷贝属性 不能替换对象
            if (t_type == "dream") {
                this.removeUsed(this.current_scheme.dream_team[index]);

                let oldTeam = this.current_scheme.dream_team[index];
                let team = TeamServer.getNewTeam();

                Object.keys(oldTeam).forEach(key => {
                    console.log("Object.keys", key, oldTeam[key], team[key])
                    oldTeam[key] = team[key];
                })
                this.$forceUpdate();
                return;
            }

            if (t_type == "free") {
                let oldTeam = this.current_scheme.free_team[index];
                let team = TeamServer.getNewTeam();

                Object.keys(oldTeam).forEach(key => {
                    console.log("Object.keys", key, oldTeam[key], team[key])
                    oldTeam[key] = team[key];
                })
                this.$forceUpdate();
                return;
            }
        },

        tohref(){
            ipcRenderer.send("open-url","https://www.wolai.com/skyey-engrave/4vDDFc3H5KSeNBnpyGrpii")
        },
    }
}
</script>
    
<style scoped>
* {
    -moz-user-select: none;
    -o-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

.warpper{
    width: 500px;
    overflow-x: hidden;
}

.menu-row {
    padding: 0 15px;
}
.menu-row .menu-btn {
    width: 90px;
    height: 30px;
    line-height: 40px;
    margin: 0;
    padding: 0;
    text-align: center;
    font-size: 12px;
    margin-bottom: 5px;
}

.title-tip{
    font-size: 11px;
    color:#646566;
}

.game-box-title /deep/.van-cell__title{
    color:rgb(22, 21, 21);
    width: 80%;
}

.my-box-title /deep/.van-cell__title{
    color:rgb(22, 21, 21);
    width: 80%;
}

.popup-title-container {
    position: absolute;
    width: 500px;
    top: 0px;
    left: 0px;
}

.popup-title-container h3 {
    display: block;
    width: 500px;
    text-align: center;    
}

.popup-content-container{
    position: absolute;
    width: 450px;
    top: 60px;
    left: 0px;
    padding:0 5%;
}

.popup-content-container .popup-file /deep/ input{
    line-height:24px;
    height: 25px;
} 

.popup-content-container .popup-btn{
    width: 100px;
    margin: auto;
}

.popup-content-container .van-button{
    width: 100px;
    margin: 0;
}

.isShowLoadSchemeDialog /deep/.van-picker .van-picker-column__item--selected{
    background-color: rgba(172, 171, 171, 0.393);
}

.isShowLoadSchemeDialog /deep/ .van-picker__title{
    cursor: default;
}

.isShowLoadSchemeDialog /deep/ li{
    cursor: pointer;
}

</style>

<style scoped>

/* 动态调整高度*/
#myTeamAutoDiv{
    height:100px;
    overflow-x: hidden;
    overflow-y: scroll;
}

#game-box{
    border:1px solid gray;
}

#my-box{
    min-height: 60px;
    border:1px solid gray;
}
.my-box-condi{
    width: 500px;
    height: 16px;
    font-size: 12px;
    margin-top: 5px;
    margin-bottom: 5px;
    text-align: center;
    overflow-x: hidden;
}

.my-box-condi .van-col{
    width: 50px;
}

.my-box-condi .van-col:last-child{
    width: 59px;
}

.box-row{
    min-height: 50px;
    padding:0 20px;
}
.game-role-headimg {
    cursor: move;
    height: 42px;
    width: 42px;
    margin: 1px;
    border: 2px double rgb(231, 216, 16);
}

.role-headimg-div {
    position: relative;
    float: left;
    height: 50px;
    width: 41px;
    margin: 1px;
    border: 1px solid darkgray;
    cursor: all-scroll;
}
.role-headimg-div .van-image{
    height: 41px;
    width: 41px;
}
.role-headimg-div span {
    display: block;
    line-height: 15px;
    height: 12px;
    width: 41px;
    text-align: center;
    font-size: 12px;
    position: absolute;
    bottom: 0;
    left: 0;
    background-color: #C0C0C0;
}

.role-headimg-div-used {
    border: 1px solid red !important;
}

.role-headimg-div-used span{
    color:red;
}

.role-headimg-div .remove {
    display: block;
    float: right;
    height: 15px;
    width: 15px;
    position: absolute;
    top: 0px;
    right: 4px;
    /* background-color: red; */
    font-size: 20px;
    border-radius: 10px;
    font-weight: bold;
    color: red;
    cursor: pointer;
    opacity: 0.5;
}


</style>

